/**
 * 
 */
package ca.uwindsor.cs.deepweb.estimation;

import java.io.IOException;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.search.Hits;

/**
 * @author Liang Jie
 * 
 */
public class DataCollectorRandomReturns extends DataCollector {

	protected short[] range;

	protected Random r;

	/**
	 * Constructor
	 * 
	 * @param fieldname
	 *            The Name of the Field in Lucene's Document that contains the
	 *            ID
	 * @param range
	 *            The upper bound and lower bound of the size of random returns
	 */
	public DataCollectorRandomReturns(String fieldname, short[] range) {
		super(fieldname);
		this.range = range;
		r = new Random();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ca.uwindsor.cs.liangjie.research.estimation.DataCollector#add(org.apache
	 * .lucene.search.Hits)
	 */
	public Set<String> add(Hits hits) {
		int_markedItemsinNewHits = 0;
		HashSet<String> newhitsids = new HashSet<String>();
		int lim = 0;
		int length = hits.length();
		do {
			lim = r.nextInt(range[1] + 1);
		} while (lim < range[0]);

		returnedItems = lim;
		// if length > lim then randomly select 'lim' IDs
		Set<Integer> set_temp = new HashSet<Integer>();
		int j = 0;
//		Random r = new Random();
		while (j < lim) {
			int index = r.nextInt(length);
			if (!set_temp.contains(index)) {
				set_temp.add(index);
				j++;

				try {
					String id = hits.doc(index).get(string_FieldName);
					if (set_UniqueItems.contains(id)) {
						int_markedItemsinNewHits++;
					}
					set_UniqueItems.add(id);
					if (isAnalyzeDocumentFrequency) {
						dfanalyzer.addID(id);
					}
					newhitsids.add(id);
				} catch (CorruptIndexException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		// calculate the total items that queried
		long_TotalItems += lim;

		// compare with last hits
		set_previousHitsID.retainAll(newhitsids);
		int_DuplicatedItemsCompareToLastQuery = set_previousHitsID.size();

		// warning
		set_previousHitsID = (HashSet<String>) newhitsids.clone();
		return newhitsids;
	}
}
